package main

import (
	"bytes"
	"encoding/gob"
	"fmt"
	"log"
)
// This example transmits a value that implements the custom encoding and decoding methods

// The Vector type has unexported fields, which the package cannot access.
// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us
// to send and receive the type with the gob package.These interfaces are defined in the "encoding" package
// We could equivalently use the locally defined GobEncode/GobDecoder interfaces.
type Vector struct {
	x, y, z int
}

func (v Vector) MarshalBinary() ([]byte, error){
	// A simple encoding: plain text.
	var b bytes.Buffer
	fmt.Fprintln(&b, v.x, v.y, v.z)  // 将各个值写入buffer,编码为utf8,值之间用空格（utf8: 32）分隔，结尾加换行LF(utf8: 10)
	return b.Bytes(), nil
}

// UnmarshalBinary modifies the recevier so it must take a pointer receiver.
func (v *Vector) UnmarshalBinary(data []byte) error {
	// A simple encoding: plain text.
	b := bytes.NewBuffer(data)
	_, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
	return err
}


func main(){
	var network bytes.Buffer // Stand-in for the network

	// Careate an encoder and send a value
	enc := gob.NewEncoder(&network)
	err := enc.Encode(Vector{3, 4, 5})
	if err != nil{
		log.Fatal("encoder:", err)
	}

	fmt.Println(network.Bytes())
	// Create a decoder and receive a value
	dec := gob.NewDecoder(&network)
	var v Vector
	err = dec.Decode(&v)
	if err != nil{
		log.Fatal("decocde:", err)
	}
	fmt.Println(v)

}




